#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/epoll.h>

#include "download.h"

int CreateTcpServe(int port)
{
	int sock = socket(AF_INET,SOCK_STREAM,0);
	struct sockaddr_in ad;
	ad.sin_family = AF_INET;
	ad.sin_port = htons(port);
//	inet_pton(AF_INET,"192.168.0.106",&ad.sin_addr.s_addr);
	ad.sin_addr.s_addr = INADDR_ANY;

	int opt = 1;
	setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));

	if(bind(sock,(struct sockaddr *)&ad,sizeof(ad)))
	{
		perror("bind error\n");
		close(sock);
		return -1;
	}

	listen(sock,5);
	return sock;
}

int download(char *buff)
{
	int ret;
	char buf[1024]={0};
	printf("%s\n",buff);
	char *q;
	char buf1[30];
	char buf2[30];
	
	buff += 1;
	q = strchr(buff,']');
	*q = '\0';
	strcpy(buf1,buff);
	buff = q + 2;
	q = strchr(buff,']');
	*q = '\0';
	strcpy(buf2,buff);
	printf("%d\n",buf1);
	int csock = (int)(buf1);
	int csock;
	struct sockaddr_in caddr;
	unsigned int len = sizeof(caddr);
	csock = accept(sock,(struct sockaddr *)&caddr,&len);
	sleep(1);

	int fd = open(buf3,O_RDONLY);
	memset(buf,0,sizeof(buf));
	if(fd == 0)
	{
		printf("open error\n");
		return 0;
	}

	while((ret = read(fd,buf,1024))>0)
	{
		send(csock,buf,ret,0);
	//	printf("%s\n",buf);
		memset(buf,0,sizeof(buf));
	}
	close(fd);
//	close(csock);
//	close(sock);
	printf("read over\n");

	return 0;
}